package com.a3dweijing.wetouch2.View;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2018/3/23.
 * 内部嵌套listview动态设定固定高度，外部为ScrollView
 */

public class AutoViewPager extends ViewPager
{
    private int current;
    
    private int height = 0;
    
    /**
     * 保存position与对于的View
     */
    private HashMap<Integer, View> mChildrenViews = new LinkedHashMap<Integer, View>();
    
    private boolean scrollble = true;
    
    public AutoViewPager(Context context)
    {
        super(context);
    }
    
    public AutoViewPager(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (mChildrenViews.size() > current)
        {
            ViewGroup child = (ViewGroup)mChildrenViews.get(current);
            ListView childAt = (ListView)child.getChildAt(0);
            ListAdapter adapter = childAt.getAdapter();
            height = 0;
            for (int i = 0; i < adapter.getCount(); i++)
            {
                View view = adapter.getView(i, null, childAt);
                view.measure(0, 0);
                int measuredHeight = view.getMeasuredHeight();
                height += measuredHeight;
            }
        }
        
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    
    public void resetHeight(int current)
    {
        this.current = current;
        if (mChildrenViews.size() > current)
        {
            
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)getLayoutParams();
            if (layoutParams == null)
            {
                layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
            }
            else
            {
                layoutParams.height = height;
            }
            setLayoutParams(layoutParams);
        }
    }
    
    /**
     * 保存position与对于的View
     */
    public void setObjectForPosition(View view, int position)
    {
        mChildrenViews.put(position, view);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        if (!scrollble)
        {
            return true;
        }
        return super.onTouchEvent(ev);
    }
    
    public boolean isScrollble()
    {
        return scrollble;
    }
    
    public void setScrollble(boolean scrollble)
    {
        this.scrollble = scrollble;
    }
}
